var currDeviceId = "";
layui.use(['element','table','form','layer','laydate'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer;

    var demo1 = xmSelect.render({
        el: '#exceptionDate',
        content: '<div id="laydate" />',
        height: 'auto',
        autoRow: true,
        on: function(data){
            if(!data.isAdd){
                dateSelect(demo1.getValue('value'));
            }
        }
    });

    laydate.render({
        elem: '#laydate',
        position: 'static',
        showBottom: false,
        format: 'yyyy-M-dd',
        change: function(){
            dateSelect(demo1.getValue('value'));
        },
        done: function(value){
            var values = demo1.getValue('value');
            var index = values.findIndex(function(val){
                return val === value
            });

            if(index !== -1){
                values.splice(index, 1);
            }else{
                values.push(value);
            }

            dateSelect(values);

            demo1.update({
                data: values.map(function(val){
                    return {
                        name: val,
                        value: val,
                        selected: true,
                    }
                })
            });
        },
        ready: removeAll,
    });
    loadCommunityList();

    function loadCommunityList() {
        $.get('/zxkDevice/loadCommunityList', {}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.communityId + "'>" + item.communityName + "</option>";
                    });
                    $("#communityId").empty().append($opt_html);
                    form.render('select');
                    loadDeviceList($("#communityId").val());
                }
            }

        });
    }

    function removeAll(){
        document.querySelectorAll('#laydate td[lay-ymd].layui-this').forEach(function(dom){
            dom.classList.remove('layui-this');
        });
    }

    function dateSelect(values){
        removeAll();
        values.forEach(function(val){
            var dom = document.querySelector('#laydate td[lay-ymd="'+val.replace(/-0([1-9])/g, '-$1')+'"]');
            dom && dom.classList.add('layui-this');
        });
    }

    addTimeTemplate = function () {
        if(!currDeviceId){
            layer.msg("请选择门禁设备",{icon:5});
            return ;
        }
        $("#resource_form")[0].reset();
        $("#upload_form").attr("disabled", false);
        $("#upload_form").attr("class", "layui-btn");
        var values = [];
        dateSelect(values);
        demo1.update({
            data: values.map(function(val){
                return {
                    name: val,
                    value: val,
                    selected: true,
                }
            })
        });
        initPage();
        layer.open({
            type: 1
            , title: '添加时间模板'
            , area: ['99%', '99%']
            , content: $('#uploadDiv')
        });
    };

    function loadDeviceList(val){
        $.get('/zxkUser/listDeviceNames', {communityId:val}, function (res) {
            if (res.status === 200) {
                let data = res.data;
                let str = '';
                for (let i = 0; i < data.length; i++) {
                    var id = data[i].ID;
                    var name = data[i].DEVICENAME;
                    if (i === 0) {
                        currDeviceId = id;
                        str += '<div style="background-color: #f1f1f1" onclick="changeUnit(this)" id="' + id + '" class="floor-item"><div class="floor-item-text">' + name + '</div></div>'
                    } else {
                        str += '<div onclick="changeUnit(this)" id="' + id + '" class="floor-item"><div class="floor-item-text">' + name + '</div></div>'
                    }
                }
                renderTable(currDeviceId);
                layui.$('.floor-group').html(str)
            }

        });
    }

    function renderTable(deviceId){
        table.render({
            elem: '#timeTemplateTable'
            ,url:'/zxkTimeTemplate/list'
            ,title: '时间模板管理'
            ,where: {'deviceId': deviceId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'id', title:'模板ID',align:'center'}
                ,{field:'name', title:'模板名称',align:'center'}
                ,{field:'updateUser', title:'修改人员',align:'center'}
                ,{field:'updateTime', title:'最后修改时间',  sort: true,templet:
                        function(data){
                            return formatTime(data.updateTime);
                        }}
                ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',width:220}
            ]]
            ,page: true
        });
    }

    function formatTime(data){
        return data ? data.replace("T", " "):"";
    }
    form.on('select(communityId)',function (data) {
        currDeviceId = "";
        loadDeviceList(data.value);
    });

    table.on('tool(timeTemplateTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'edit':
                $.get('/zxkTimeTemplate/getTimeTemplate',{id:data.id,deviceId:currDeviceId},function (res) {
                    if(res && res.status === 200 ){
                        var exTimeList = res.data.exTimeList;
                        dateSelect(exTimeList);
                        demo1.update({
                            data: exTimeList.map(function(val){
                                return {
                                    name: val,
                                    value: val,
                                    selected: true,
                                }
                            })
                        });
                        // 布防时间
                        setData(res.data.bfTimes)
                    }
                });
                $("#update_form").attr("disabled", false);
                $("#update_form").attr("class", "layui-btn");
                $("#id").val(data.id);
                $("#templateName").val(data.name);
                var radio = document.getElementsByName("enabled");
                for (var i = 0; i < radio.length; i++) {
                    if(data.enabled == radio[i].value){ //这里不能用===
                        $(radio[i]).next().click();
                    }
                }
                form.render();
                layer.open({
                    type: 1
                    , title: '编辑时间模板'
                    , area: ['99%', '99%']
                    , content: $('#uploadDiv')
                });
                break;
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    layer.load();
                    $.get('/zxkTimeTemplate/delete',{id:data.id,deviceId:currDeviceId},function (res) {
                        layer.msg(res.msg,{
                            time:1000,
                            end:function () {
                                table.reload('timeTemplateTable');
                                layer.closeAll();
                            }
                        });
                    });
                });
                break;

        }
    });

    form.on('submit(upload_form)',function(data){
        $("#upload_form").attr("disabled", true);
        $("#upload_form").attr("class", "layui-btn layui-btn-disabled");
        var exTimeArr = demo1.getValue();
        var exArr = [];
        for(var i in exTimeArr){
            var obj = {"id":exTimeArr[i].value,"name":exTimeArr[i].name};
            exArr.push(obj);
        }
        data.field.deviceId = currDeviceId;
        data.field.exceptionDate = JSON.stringify(exArr);
        data.field.bfTimeStr = JSON.stringify(getData());
        //[{"id":"2021-2-02","name":"2021-2-02"},{"id":"2021-2-05","name":"2021-2-05"},{"id":"2021-2-03","name":"2021-2-03"}]
        layer.load();
        $.ajax({
            type: 'post',
            url: '/zxkTimeTemplate/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },500);
                $("#upload_form").attr("disabled", false);
                $("#upload_form").attr("class", "layui-btn");
                table.reload('timeTemplateTable');
            }
        });
        return false;
    });

    $("#cancel_form").on('click',function (){
        layer.closeAll();
        return false;
    });

});

function reload(){
    location.reload();
}

function changeUnit(e) {
    currDeviceId = layui.$(e).attr('id');
    layui.$('.floor-item').css('background-color', 'transparent')
    layui.$(e).css('background-color', '#f1f1f1')
    layui.table.reload('timeTemplateTable', {
        page: {
            curr: 1
        },
        where: {'deviceId': layui.$(e).attr('id')}
    });
}
